<template>
  <div>
    <el-tree
      ref="layerTree"
      :data="treeData"
      show-checkbox
      node-key="pkid"
      default-expand-all
      @check="handleCheck"
      @node-click="handleNodeClick"
      :filter-node-method="filterNode"
    >
      <!--      :default-checked-keys='defaultCheckedKeys'-->
      <div
        slot-scope="{ node, data }"
        style="
          color: white;
          display: flex;
          width: 100%;
          overflow: hidden;
        "
      >
        <icon
          v-if="data.catalogName"
          :title="'文件夹'"
          :name="'wenjianjia'"
          :color="'#A7BECA'"
        />
        <icon
          v-if="data.sourceName"
          :title="'数据服务'"
          :name="'shujufuwu'"
          :color="'#A7BECA'"
        />
        <!--        <el-tooltip-->
        <!--          effect="dark"-->
        <!--          :content="data.sourceName || data.catalogName"-->
        <!--          placement="top"-->
        <!--        >-->
        <span
          v-if="data.sourceName"
          @click="handleCheck"
          class="margin"
          >{{ data.sourceName }}</span
        >
        <span v-if="data.catalogName" class="margin">{{
          data.catalogName
        }}</span>
        <!--        </el-tooltip>-->
      </div>
    </el-tree>
  </div>
  <!--  :props="defaultProps"-->
  <!--  @check="handleCheck"-->
</template>

<script>
import { treeByTypeId } from '@/api/tree'
import { getAction } from '@/utils/helper'
import Icon from '@/components/icon/index'

export default {
  components: {
    Icon
  },
  props: {
    treeTypeName: {
      type: String,
      default: ''
    },
    viewerId: {
      type: String,
      default: ''
    },
    filter: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 树组件相关
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'catalogName',
        disabled: (_data, node) => {
          return this.loadingList.includes(node.key)
        }
      },
      // 默认加载的图层列表
      defaultCheckedKeys: [],
      // 上一次加载的图层树节点列表
      lastCheckedNodes: [],
      // 正在加载的图层id数组
      loadingList: []
    }
  },
  computed: {
    treeTypeObj() {
      if (this.treeTypeName !== '') {
        console.log(this.treeTypeName)
        if (
          this.$store.state.tree.treeType[this.treeTypeName]
        ) {
          return {
            keys: [this.treeTypeName],
            values: [
              this.$store.state.tree.treeType[
                this.treeTypeName
              ]
            ]
          }
        }
      } else {
        return {
          keys: Object.keys(
            this.$store.state.tree.treeType
          ),
          values: Object.values(
            this.$store.state.tree.treeType
          )
        }
      }
    }
  },
  watch: {
    treeTypeObj: {
      handler(treeTypeObj) {
        if (treeTypeObj && treeTypeObj.keys.length !== 0) {
          this.getTreeData(treeTypeObj)
        }
      },
      immediate: true
    },
    filter: {
      handler(value) {
        this.$refs.layerTree.filter(value)
      }
    }
  },
  async created() {
    const { layerManager } = await getAction(this.viewerId)
    this.layerManager = layerManager
    // 已加载图层赋值
    this.layerManager.layers.forEach((item) => {
      this.defaultCheckedKeys.push(item.id)
    })
    this.$refs.layerTree.setCheckedKeys(
      this.defaultCheckedKeys
    )
    // console.log('默认选中', this.defaultCheckedKeys)
    // 监听添加删除
    this.layerManager.on('add', ({ id }) => {
      this.loadingList = this.loadingList.filter(
        (item) => item !== id
      )
      this.$bus.$emit('removeAdd', id)
    })
    this.layerManager.on('del', (id) => {
      this.$nextTick(() => {
        if (this.$refs.layerTree) {
          this.$refs.layerTree.setChecked(id, false)
        }
        this.lastCheckedNodes =
          this.lastCheckedNodes.filter((item) => {
            return item.pkid !== id
          })
        this.$bus.$emit('removeLayer', id)
      })
    })
  },
  mounted() {},
  methods: {
    getTreeData(treeTypeObj) {
      treeByTypeId(treeTypeObj.values[0]).then((res) => {
        if (res.success) {
          this.treeData = res.data[0].children
          this.addResourceInfo(this.treeData)
        }
      })
    },
    addResourceInfo(data) {
      data.forEach((item) => {
        // item.child = []
        // if (item.resourceInfo) {
        //   item.child = item.child
        //     .concat(item.children)
        //     .concat(item.resourceInfo)
        // }
        // if (item.children.length) {
        //   this.addResourceInfo(item.children)
        // }

        if (item.resourceInfo) {
          item.children = item.children.concat(
            item.resourceInfo
          )
        }
        if (item.children && item.children.length) {
          this.addResourceInfo(item.children)
        }
      })
    },
    handleCheck(_currentNode, checkedNodes) {
      // 开始处理增加和移除的图层
      console.log('_currentNode ', _currentNode)
      console.log('checkedNodes', checkedNodes)
      // 解决驾驶舱子路由切换后无法移除服务的问题
      if (
        checkedNodes.checkedNodes.indexOf(_currentNode) ===
        -1
      ) {
        this.layerManager.del(_currentNode.pkid)
      }
      this.$emit(
        'handleCheckList',
        checkedNodes.checkedNodes.filter((item) => {
          return item.sourceName
        }),
        _currentNode
      )
      if (!_currentNode.sourceName) {
        this.$emit('handleCheck', false)
        // return
      }
      const newArr = checkedNodes.checkedNodes.filter(
        (item) => !item.children
      )
      // console.log('newArr', newArr)
      if (newArr.length === 0) {
        // 没有一条选中数据时关闭右侧echarts
        this.$emit('handleCheck', false)
        // return
      }
      const oldArr = [...this.lastCheckedNodes]
      // if (oldArr.length === 0 && this.defaultCheckedKeys.length > 0) {
      //   this.defaultCheckedKeys.forEach((key) => {
      //     oldArr.push(this.$refs.layerTree.getNode(key).data)
      //   })
      //   console.log('重新赋值', oldArr)
      // }
      // console.log('oldArr', oldArr)
      // if (this.treeTypeName === 'BIM') {
      //   if (checkedNodes.checkedNodes.length > 0) {
      //     newArr = [_currentNode];//选择图层
      //     if (this.$refs.layerTree && checkedNodes) { //bim树单选
      //       this.$nextTick(function () {
      //         console.log('_currentNode----------', _currentNode, checkedNodes);
      //         if (checkedNodes.checkedNodes.length > 1) {
      //           checkedNodes.checkedNodes.forEach((item) => {
      //             if (item.pkid !== _currentNode.pkid) {
      //               this.$refs.layerTree.setChecked(item.pkid, false);//setCheckedNodes([_currentNode.id])
      //             }
      //           })
      //         }
      //       })
      //     }
      //   } else {
      //     newArr = [];
      //   }
      //   this.$emit("checkedBimData", newArr);
      // }
      if (this.treeTypeName === 'BIM') {
        if (
          checkedNodes.checkedNodes.indexOf(
            _currentNode
          ) !== -1
        ) {
          console.log('BIM', true)
          this.$emit('checkedBimData', [_currentNode])
        } else {
          console.log('BIM', false)
          this.$emit('checkedBimData', [])
        }
      }
      newArr.forEach((newItem) => {
        const index = oldArr.findIndex(
          (oldItem) => oldItem.pkid === newItem.pkid
        )
        if (index > -1) {
          // 取消选中时关闭右侧echarts
          this.$emit('handleCheck', false)
          oldArr.splice(index, 1)
        } else {
          this.$emit('handleCheck', true)
          // const { pkid, type, height = 0 } = newItem
          // 加载开始 禁用子节点
          this.loadingList.push(newItem.pkid)
          // this.layerManager.add({
          //   ...newItem,
          //   // type: this.$store.state.tree.treeTypeId[type],
          //   type: type,
          //   data: newItem.serviceUrl || '',
          //   height,
          //   onClick: ({ entity, position, title }) => {
          //     console.log(entity, position, title)
          //   }
          // })
          const parent = this.treeData.find(
            (item) => item.pkid === newItem.catalogId
          )
          if (parent) {
            newItem.from = parent.type
          }
          this.layerManager.add(newItem)
        }
      })
      oldArr.forEach((oldItem) => {
        this.layerManager.del(oldItem.pkid)
      })
      this.lastCheckedNodes = newArr

      // console.log('=======')
      // console.log('newArr', newArr)
      // console.log('oldArr', oldArr)
      // console.log('lastCheckedNodes', this.lastCheckedNodes)
    },
    handleNodeClick(data, node, el) {
      this.$emit('handleNodeClick', data, node, el)
    },
    // bim:设置节点选中
    setNodeChecked(id) {
      if (this.$refs.layerTree) {
        // console.log('setNodeChecked', id);
        this.$refs.layerTree.setChecked(id, true)
      }
    },
    filterNode(value, data) {
      console.log('filterNode', value, data)
      if (!value) return true
      if (data.sourceName) {
        return data.sourceName.indexOf(value) !== -1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-checkbox {
    margin-right: 5px !important;
  }

  .margin {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
